# subsystem_manager.py
import os
import subprocess
from datetime import datetime

class SubsystemCreator:
    def __init__(self, server_ip, allowed_images):
        self.server_ip = server_ip
        self.allowed_images = allowed_images
        self.base_dir = os.path.join(os.path.expanduser("~"), "QuickResearch")
        print("初始化 SubsystemCreator: server_ip={}, allowed_images={}, base_dir={}".format(self.server_ip, self.allowed_images, self.base_dir))

    def check_and_occupy_ports(self, port1, port2):
        print("检查端口: port1={}, port2={}".format(port1, port2))
        if port1 == port2:
            raise ValueError("端口1和端口2不能相同。")

        for port in (port1, port2):
            if not (8101 <= port <= 20000):
                raise ValueError("端口 {} 不在允许范围 8101-20000 内。".format(port))
            # 检查端口是否被占用
            result = subprocess.run(['netstat', '-tuln'], stdout=subprocess.PIPE, universal_newlines=True)
            print("netstat 结果: {}".format(result.stdout))
            if ":{} ".format(port) in result.stdout:
                raise ValueError("端口 {} 被占用。".format(port))
        print("端口 {} 和 {} 检查通过，未被占用。".format(port1, port2))

    def extract_image_name(self, docker_image_name):
        return docker_image_name.split(':')[1]

    def create_subsystem(self, username, docker_image_name, port1, port2, subsystem_username='handsfree', subsystem_password='handsfree', custom_params=''):
        image_name = self.extract_image_name(docker_image_name)
        print("创建子系统: username={}, docker_image_name={}, image_name={}, port1={}, port2={}, custom_params={}".format(username, docker_image_name, image_name, port1, port2, custom_params))
        if docker_image_name not in self.allowed_images:
            raise ValueError("镜像名称 '{}' 不在允许列表中: {}".format(docker_image_name, ', '.join(self.allowed_images)))

        # 检查并占用端口
        self.check_and_occupy_ports(port1, port2)

        # 创建用户目录
        subdir = os.path.join(self.base_dir, username, "{}-{}".format(image_name, port1))
        print("创建用户目录: {}".format(subdir))
        os.makedirs(subdir, exist_ok=True)
        os.chmod(subdir, 0o777)

        container_name = "{}-{}-{}".format(username, image_name, port1)

        # 准备docker run命令，custom_params 直接接在 --name 后面
        docker_run_cmd = 'docker run -d --name "{}" {} -v "{}:/home/{}" -p "{}:8081" -p "{}:8082" "{}"'.format(
            container_name, custom_params, subdir, subsystem_username, port1, port2, docker_image_name)

        print("即将执行的命令是：")
        print(docker_run_cmd)

        # 执行docker run命令
        subprocess.run(docker_run_cmd, shell=True, check=True)
        print("子系统远程桌面网页地址: http://{}:{}".format(self.server_ip, port1))
        print("子系统远程IDE网页地址: https://{}:{}".format(self.server_ip, port2))
        print("子系统用户名: {}".format(subsystem_username))
        print("子系统登录密码: {}".format(subsystem_password))

class SubsystemDeleter:
    def __init__(self):
        self.base_dir = os.path.join(os.path.expanduser("~"), "QuickResearch")
        print("初始化 SubsystemDeleter: base_dir={}".format(self.base_dir))

    def extract_image_name(self, docker_image_name):
        return docker_image_name.split(':')[1]

    def delete_subsystem(self, username, docker_image_name, port1):
        image_name = self.extract_image_name(docker_image_name)
        print("删除子系统: username={}, docker_image_name={}, image_name={}, port1={}".format(username, docker_image_name, image_name, port1))
        container_name = "{}-{}-{}".format(username, image_name, port1)
        
        # 检查容器是否存在
        if not self.container_exists(container_name):
            raise ValueError("容器 {} 不存在".format(container_name))

        # 停止并删除容器
        subprocess.run(['docker', 'stop', container_name], check=True)
        subprocess.run(['docker', 'rm', container_name], check=True)
        print("容器 {} 已停止并删除".format(container_name))

        user_data_dir = os.path.join(self.base_dir, username, "{}-{}".format(image_name, port1))
        print("用户数据目录: {}".format(user_data_dir))

        if os.path.exists(user_data_dir):
            timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
            backup_dir = "{}_{}".format(user_data_dir, timestamp)
            os.rename(user_data_dir, backup_dir)
            print("用户数据已备份到 {}".format(backup_dir))
        else:
            print("用户数据目录 {} 不存在。".format(user_data_dir))

        print("子系统 {} 已删除".format(container_name))

    def container_exists(self, container_name):
        print("检查容器是否存在: {}".format(container_name))
        result = subprocess.run(['docker', 'ps', '-a', '--format', '{{.Names}}'], stdout=subprocess.PIPE, universal_newlines=True)
        print("docker ps 结果: {}".format(result.stdout))
        return container_name in result.stdout.split()
